package com.whu.waterworks.service;

import java.lang.reflect.InvocationTargetException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.apache.commons.beanutils.PropertyUtils;

import com.whu.waterworks.dao.HistorydataDAO;
import com.whu.waterworks.dao.RealtimedataDAO;
import com.whu.waterworks.model.Historydata;
import com.whu.waterworks.model.HistorydataId;
import com.whu.waterworks.model.Realtimedata;
import com.whu.waterworks.model.RealtimedataId;
import com.whu.waterworks.util.DateUtil;
/**
 * 
 * @author wangying
 *
 */
public class DataService {
	private RealtimedataDAO realtimedataDAO;
	private HistorydataDAO historydataDAO;
	private DateUtil dateUtil;
	
	/**
	 * 保存数据
	 * @author wangying
	 * @param entity
	 * @return
	 */
	public boolean saveDataRealTime(Realtimedata entity)
	{
		//System.out.println("dataService entity="+entity.getId().getStationnum()+" "+entity.getId().getTime());
		boolean result = realtimedataDAO.save(entity);
		//System.out.println("dataService save result="+result);
		return result;
	}
	
	public String saveData(String type,String time,String stationCode, String value)
	{
		try {		
			Realtimedata realtimedata = getTodayWaterDataByIdType(stationCode, type);
			Realtimedata rd = new Realtimedata();			
			RealtimedataId realtimedataId = new RealtimedataId();			
			realtimedataId.setStationnum(stationCode);
			realtimedataId.setTime(time);
			realtimedataId.setType(type);
			rd.setId(realtimedataId);
			rd.setValue(value);
			
			Historydata hd = new Historydata();
			HistorydataId historydataId = new HistorydataId();
			historydataId.setStationnum(stationCode);
			historydataId.setTime(time);
			historydataId.setType(type);
			hd.setId(historydataId);
			hd.setValue(value);
			System.out.println("%%%%%%SaveData realtimedata="+realtimedata);
			if(realtimedata!=null )//如果实时数据库里面存在，则替换，并且更新历史
			{							
				Historydata hd1 = new Historydata();
				HistorydataId historydataId1 = new HistorydataId();
				historydataId1.setStationnum(realtimedata.getId().getStationnum());
				historydataId1.setTime(realtimedata.getId().getTime());
				historydataId1.setType(realtimedata.getId().getType());
				hd1.setId(historydataId1);
				hd1.setValue(realtimedata.getValue());
				
				deleteDataHistory(hd1);//先删除历史表中的数据
				deleteDataRealTime(realtimedata);
				saveDataRealTime(rd);//插入实时表中
				saveDataHistory(hd);//插入历史表中
			}
			else {//不存在，同时插入实时历史表	
				saveDataRealTime(rd);//插入实时表中
				saveDataHistory(hd);//插入历史表中		
			}
			return "SUCCESS";
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			return "FAIL";
			
		}
	}
	/**
	 * 更新实时数据库
	 * @author wangying
	 * @param entity
	 * @return
	 */
	public boolean updateDataRealTime(Realtimedata entity)
	{
		return realtimedataDAO.update(entity);
	}
	/**
	 * 更新历史数据
	 * @author wangying
	 * @param entity
	 * @return
	 */
	public boolean updateDataHistory(Historydata entity)
	{
		
		boolean result= historydataDAO.update(entity);
		//System.out.println("dataService save result="+result);
		return result;
	}
	/**
	 * 保存历史数据
	 * @author wangying
	 * @param entity
	 * @return
	 */
	public boolean saveDataHistory(Historydata entity)
	{
		boolean result= historydataDAO.save(entity);
		//System.out.println("dataService save result="+result);
		return result;
	} 
	/**
	 * 删除实时数据库
	 * @author wangying
	 * @param entity
	 * @return
	 */
	public boolean deleteDataRealTime(Realtimedata entity)
	{
		return realtimedataDAO.delete(entity);
	}
	
	/**
	 * 删除历史数据库
	 * @author wangying
	 * @param entity
	 * @return
	 */
	public boolean deleteDataHistory(Historydata entity)
	{
		return historydataDAO.delete(entity);
	}
	
	/**
	 * 根据时间段得到指定id的指定类型数据
	 * @author wangying
	 * @param id
	 * @param type
	 * @param beginTime
	 * @param endTime
	 * @return
	 */
	public List<Realtimedata> getDataByTwoTime(String id,String type,String beginTime,String endTime)
	{
		List<Realtimedata> resutDatas = new ArrayList<>();
		String begin = beginTime+"/"+"00:00:00";
		String end = endTime +"/"+"24:00:00";
		dateUtil = new DateUtil();
		//SimpleDateFormat format = new SimpleDateFormat("yyyy/MM/dd");
		/*Date endDate = format.parse(endTime);
		if(dateUtil.isToday(endDate))//结束时间为今天，则涉及两个历史表和实时表
		{
			List<Realtimedata> realtimedatas = realtimedataDAO.findByIdTodayAll(id, type);
			if(realtimedatas!=null && realtimedatas.size()>0)
			{
				System.out.println("Data Service realtimedatas.size()="+realtimedatas.size());
				resutDatas.addAll(realtimedatas);
			}
			List<Historydata> historydatas = historydataDAO.findByIdAllTime(id, type, begin);
			//如果有历史数据，则将历史数据加入
			if(historydatas!=null && historydatas.size()>0)
			{
				System.out.println("Data Service historydatas.size()="+historydatas.size());
				for(Historydata historydata:historydatas)
				{
					Realtimedata temp = new Realtimedata();
					RealtimedataId tId = new RealtimedataId();
					
					try {
						PropertyUtils.copyProperties(tId,historydata.getId());
					} catch (IllegalAccessException | InvocationTargetException
							| NoSuchMethodException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					temp.setId(tId);
					temp.setValue(historydata.getValue());
					resutDatas.add(temp);
				}
			}
		}
		else*/ {//只涉及历史表
			List<Historydata> historydatas = historydataDAO.findByIdAllInTime(id, type, end, begin);
			//如果有历史数据，则将历史数据加入
			if(historydatas!=null && historydatas.size()>0)
			{
				for(Historydata historydata:historydatas)
				{
					Realtimedata temp = new Realtimedata();
					RealtimedataId tId = new RealtimedataId();
					
					try {
						PropertyUtils.copyProperties(tId,historydata.getId());
					} catch (IllegalAccessException | InvocationTargetException
							| NoSuchMethodException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					temp.setId(tId);
					temp.setValue(historydata.getValue());
					resutDatas.add(temp);
				}
			}
		}	
		return resutDatas;
	}
	/**
	 * 获取实时表中指定id指定类型的最新数据（实时数据库表只存最新的一条数据）
	 * @author wangying
	 * @param id
	 * @param type
	 * @return
	 */
	public Realtimedata getTodayWaterDataByIdType(String id,String type)
	{
		List<Realtimedata> realtimedatas = new ArrayList<>();
		System.out.println("Data service getTodayWaterDataById");
		realtimedatas = realtimedataDAO.findByIdTodayAll(id, type);
		if(realtimedatas!=null && realtimedatas.size()>0)
		{
			return realtimedatas.get(0);
		}
		return null;
	}
	
	/**
	 * 获取所有实时表里面的所有数据
	 * @author wangying
	 * @return
	 */
	public List<Realtimedata> getAllRealTimeData()
	{
		List<Realtimedata> realtimedatas = new ArrayList<>();
		realtimedatas = realtimedataDAO.findAll();
		return realtimedatas;
	}
	/**
	 * 获取所有实时表里面指定id的所有数据
	 * @author wangying
	 * @param id
	 * @return
	 */
	public List<Realtimedata> getAllRealTimeDataById(String id)
	{
		List<Realtimedata> realtimedatas = new ArrayList<>();
		realtimedatas = realtimedataDAO.findAllById(id);
		return realtimedatas;
	}
	public RealtimedataDAO getRealtimedataDAO() {
		return realtimedataDAO;
	}

	public void setRealtimedataDAO(RealtimedataDAO realtimedataDAO) {
		this.realtimedataDAO = realtimedataDAO;
	}

	public HistorydataDAO getHistorydataDAO() {
		return historydataDAO;
	}

	public void setHistorydataDAO(HistorydataDAO historydataDAO) {
		this.historydataDAO = historydataDAO;
	}

}
